package com.fept.msgcore.msgserver.netty.server;

import com.fept.msgcore.msgserver.netty.handler.BaseMessageHandler;
import com.fept.msgcore.msgserver.netty.handler.BaseMessageHandlerFactory;
import com.fept.msgcore.msgserver.netty.handler.DecoderFactory;
import com.fept.msgcore.msgserver.netty.handler.EncoderFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;

/**
 * Created by Srma on 1/13/2017.
 */
public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {
    private String name;
    private EncoderFactory encoderFacotry;
    private DecoderFactory decoderFactory;
    private BaseMessageHandlerFactory baseMessageHandlerFactory;

    public NettyServerInitializer(String name, EncoderFactory encoderFacotry, DecoderFactory decoderFactory, BaseMessageHandlerFactory baseMessageHandlerFactory) {
        this.setName(name);
        this.encoderFacotry = encoderFacotry;
        this.decoderFactory = decoderFactory;
        this.baseMessageHandlerFactory = baseMessageHandlerFactory;
    }

    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        BaseMessageHandler baseMessageHandler = this.baseMessageHandlerFactory.newBaseMessageHandler();
        pipeline.addLast(new ChannelHandler[]{new ReadTimeoutHandler(baseMessageHandler.getReadTimeout())});
        pipeline.addLast(new ChannelHandler[]{new WriteTimeoutHandler(baseMessageHandler.getWriteTimeout())});
        pipeline.addLast("encoder", this.encoderFacotry.newEncoder());
        pipeline.addLast("decoder", this.decoderFactory.newDecoder());
        pipeline.addLast("handler", baseMessageHandler);
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
